<?php

namespace app\common\model;

class ChannelCarrier extends BaseModel
{
    protected $pk = 'carrier_id';

    protected $autoWriteTimestamp = 'datetime';

    // 设置 json 字段
    protected $json = ['ext_json'];

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 状态开启
     */
    const STATUS_Y = 1;

    /**
     * 状态关闭
     */
    const STATUS_N = 0;

    public static $CARRIER_STATUS = [
        self::STATUS_Y => '开启',
        self::STATUS_N => '关闭',
    ];

    /**
     * 预充值
     */
    const PAY_BEFORE = 0;

    /**
     * 现结
     */
    const PAY_ING = 1;

    /**
     * 银行转账
     */
    const PAY_BANK = 5;

    /**
     * 支付宝
     */
    const PAY_ALI = 10;

    /**
     * 账期
     */
    const PAY_AFTER = 15;

    /**
     * 其它支付
     */
    const PAY_OTHER = 20;

    public static $PAY_TYPE = [
        self::PAY_BEFORE => '预充值',
        self::PAY_ING => '现结',
        self::PAY_BANK => '银行转账',
        self::PAY_ALI => '支付宝',
        self::PAY_AFTER => '账期',
        self::PAY_OTHER => '其它支付',
    ];

    protected function setPayTypeAttr($value)
    {
        $temp = array_flip(self::$PAY_TYPE);
        return isset($temp[$value]) ? $temp[$value] : $value;
    }

    protected function getPayTypeAttr($value)
    {
        return isset(self::$PAY_TYPE[$value]) ? self::$PAY_TYPE[$value] : $value;
    }

    protected function setCreateByAttr()
    {
        if($this->isCli) return 0;
        $admin = session('lmterp');
        return $admin ? $admin->id : 0;
    }

    protected function setUpdateByAttr()
    {
        if($this->isCli) return 0;
        $admin = session('lmterp');
        return $admin ? $admin->id : 0;
    }

    public function channels()
    {
        return $this->hasMany(Channel::class, 'carrier_id', 'carrier_id');
    }

    /**
     * 获取所有承运商
     * @return array|\PDOStatement|string|\think\Collection
     * @date 2020/09/15
     * @author longli
     */
    public static function getAll()
    {
        return static::where(['status' => self::STATUS_Y])->order("sort desc, carrier_name")->select();
    }
}
